package eaa.tgi.scrum.repositories;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import eaa.tgi.scrum.domain.Message;

@Repository
public class MessageRepository {

	protected EntityManager entityManager;
	
	@PersistenceContext
	public void setEntityManager(EntityManager entityManager) {
		this.entityManager = entityManager;
	}
	
	public List<Message> getMessages(Long projectId) {
		
		try {
		
			List<Message> messages = (List<Message>) entityManager.createQuery("SELECT m FROM Message m WHERE project.id = :project")
										.setParameter("project", projectId).getResultList();
		
			return messages;
			
		} catch (NoResultException userNotFoundException) {
			return null;
		}
	}
	
	@Transactional
	public void persist(Message message) {
		this.entityManager.persist(message);
	}
}
